import React, { useEffect, useState } from "react";
import './repay.css';
import '../../../App.css'
import { useHistory } from "react-router-dom/cjs/react-router-dom";
import { Mask, DotLoading } from "antd-mobile";
import { useDispatch, useSelector } from "react-redux";
import icon_checked from "@/assets/icon_checked.png"
import icon_uncheck from "@/assets/icon_uncheck.png"
import icon_repay_rollover from "@/assets/icon_repay_rollover.png"
import { REPAY_BILL_REQ_FAIL, REPAY_BILL_REQ_SUCCESS, getRepayDetail } from "@/store/actions/repayDetail";
import { REPAY_URL_REQ_FAIL, REPAY_URL_REQ_SUCCESS, getRepayUrl } from "@/store/actions/repayUrl";
import { saveEvent } from "@/store/actions/saveEvent";
import AddFavorite from "@/components/AddFavorite";
import AddHomeEvent from "@/utils/addHomeEvent";
import AddToHomeGifDialog from "@/components/AddToHomeGifDialog/AddToHomeGifDialog";
import NavigateBarRepay from "@/components/NavigateBarRepay/NavigateBarRepay";
import { REPAY_USER_STATE_REQ_FAIL, REPAY_USER_STATE_REQ_SUCCESS, getUserState } from "@/store/actions/userState";
import { PageTag } from "@/utils/pageTag";
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";
import PaidAskDialog from "@/components/PaidAskDialog/PaidAskDialog";


/**
 * 还款页
 */
export default function Repay() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    //显示支付提示弹框
    const [paidAskMaskVisible, setPaidAskMaskVisible] = useState(false);

    // 获取路由历史 history 对象
    const history = useHistory()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //获取Redux Store中的信息
    const repayDetailInfo = useSelector(state => state.repayDetail)

    //获取Redux Store中的信息
    const repayUrlInfo = useSelector(state => state.repayUrl)

    //获取Redux Store中的用户状态信息
    const userNotExistInfo = useSelector(state => state.userNotExist)

    //获取Redux Store中的用户状态信息
    const userStateInfo = useSelector(state => state.userState)

    //确认申请
    const doRepay = async () => {
        console.log("doRepay: ");

        //确认申请
        try {
            //获取Action
            const action = getRepayUrl()

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //点击提交
    const onHandleSubmit = () => {
        //打点
        doHitEvent("REPAY_COMMIT_CLICK")

        //显示loading
        setMaskVisible(true)
        //获取还款链接
        doRepay()
    }

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        console.log(`点击add home监听: ${type}`)
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        console.log(`点击close add home监听`)
        setAddHomeMaskVisible(false)
    }

    // 刷新操作
    const onHandleRefresh = () => {
        // 查询用户流程状态
        checkUserStateInfo()
    }

    // 关闭支付提示弹框
    const onHandlePaidAskDialogClose = () => {
        // 关闭弹框
        setPaidAskMaskVisible(false)
    }

    //已支付
    const onHandleDidPaid = () => {
        // 关闭弹框
        setPaidAskMaskVisible(false)

        // 查询状态
        checkUserStateInfo()
    }

    // 未支付
    const onHandleNotPaid = () => {
        setPaidAskMaskVisible(false)
    }

    //查询用户流程状态
    const checkUserStateInfo = async () => {
        console.log("REPAY-checkUserStateInfo: ");

        //获取用户状态
        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getUserState(PageTag.REPAY)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //查询还款信息
    const checkRepayInfo = async () => {
        console.log("REPAY-checkRepayInfo: ");

        //获取用户状态
        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getRepayDetail()

            //触发接口
            dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //启动请求
    useEffect(() => {
        //获取贷款详情
        try {
            // 查询用户状态
            checkUserStateInfo()

            //打点
            doHitEvent("REPAY_START")

            return () => {
                //打点
                doHitEvent("REPAY_END")
            }
        } catch (e) {
            console.log(e)
        }
    }, [])

    //获取还款详情成功返回
    useEffect(() => {
        //获取还款详情成功返回
        if (repayDetailInfo.status === REPAY_BILL_REQ_SUCCESS) {
            console.log("Repay-还款详情获取成功")
            console.log(repayDetailInfo)
            //关闭loading
            setMaskVisible(false)

        } else if (repayDetailInfo.status === REPAY_BILL_REQ_FAIL) {
            //关闭loading
            setMaskVisible(false)
        }
    }, [repayDetailInfo])

    //获取还款链接功返回
    useEffect(() => {
        //获取还款链接功返回
        if (repayUrlInfo.status === REPAY_URL_REQ_SUCCESS) {
            console.log("Repay-还款链接获取成功")
            console.log(repayUrlInfo)

            // 显示支付询问弹框
            setPaidAskMaskVisible(true)

            setTimeout(() => {
                //关闭loading
                setMaskVisible(false)

                const url = repayUrlInfo.url
                window.open(url, "_blank")
            }, 500)

        } else if (repayUrlInfo.status === REPAY_URL_REQ_FAIL) {
            //关闭loading
            setMaskVisible(false)
        }
    }, [repayUrlInfo])

    // 查询用户流程状态返回监听
    useEffect(() => {
        try {

            console.log("REPAY-查询用户流程状态返回监听")
            console.log(userStateInfo)

            if (userStateInfo.status === REPAY_USER_STATE_REQ_SUCCESS) {
                //隐藏loading
                setMaskVisible(false)

                console.log("LOAING-再次查询user state:")
                console.log("LOAING-applyStatus: " + userStateInfo.applyStatus)
                console.log("LOAING-orderStatus: " + userStateInfo.orderStatus)
                console.log("LOAING-signFlag: " + userStateInfo.signFlag)
                console.log("Launch-signOrderId: " + userStateInfo.signOrderId)

                //是否为签约中
                const isHomeSigning = isLoanSigning(userStateInfo.signFlag, userStateInfo.signOrderId)
                //是否为审核中
                const isHomeReviewing = isLoanReviewing(userStateInfo.applyStatus)
                //是否为拒绝
                const isHomeReject = isLoanReject(userStateInfo.applyStatus, userStateInfo.orderStatus)
                //是否为放款中
                const isHomeLoaning = isLoanLoaning(userStateInfo.orderStatus)
                //是否为待还款
                const isHomeRepay = isLoanRepayNow(userStateInfo.orderStatus)
                //是否为待进件
                const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay))
                console.log("LOAING-isHomeReviewing: " + isHomeReviewing)
                console.log("LOAING-isHomeReject: " + isHomeReject)
                console.log("LOAING-isHomeLoaning: " + isHomeLoaning)
                console.log("LOAING-isHomeRepay: " + isHomeRepay)
                console.log("LOAING-isHomeNotLoan: " + isHomeNotLoan)
                console.log("LOAING-isHomeSigning: " + isHomeSigning)

                //页面转发
                setTimeout(() => {
                    if (isHomeSigning) {
                        history.replace('/guide')
                    } else if (isHomeReviewing) {
                        history.replace('/review')
                    } else if (isHomeReject) {
                        history.replace('/reject')
                    } else if (isHomeLoaning) {
                        history.replace('/loaning')
                    } else if (isHomeRepay) {
                        //获取还款信息
                        checkRepayInfo()

                    } else {
                        history.replace('/home')
                    }
                }, 500)

            } else if (userStateInfo.status === REPAY_USER_STATE_REQ_FAIL) {
                //隐藏loading
                setMaskVisible(false)
            }
        } catch (e) {
            console.log(e)
        }
    }, [userStateInfo])

    //监听用户是否存在
    useEffect(() => {
        if (userNotExistInfo.notExist === true) {
            history.replace('/login')
            // history.replace('/loginfb')
        }
    }, [userNotExistInfo])

    return (
        <div className="repayRoot">
            <NavigateBarRepay theme="white" onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} onRefresh={onHandleRefresh}>Remboursement du prêt</NavigateBarRepay>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="repayTopEdge"></div>

            <div className="repayContent">

                <div className="repayContentScroll">
                    <div className="repayPlan">
                        <div className="repayPlanHeader">
                            <div className="repayPlanHeaderContent">
                                <img
                                    className="repayPlanHeaderIcon"
                                    src={icon_checked}
                                    alt="" />
                                <span className="repayItemHeaderTitle">Effectuer le paiement intégral:</span>
                            </div>
                            <span className="repayItemHeaderTips">Vous pouvez emprunter à nouveau immédiatement après le remboursement.</span>
                        </div>

                        {/* 还款信息 */}
                        <div className="repayItemList">
                            <div className="repayItemBillContent">
                                <span className="repayItemBillHeaderTitle">Remboursement total</span>
                                <span className="repayItemBillHeaderAmount">{repayDetailInfo.repayAmount} {repayDetailInfo.currency}</span>
                                <span className="repayItemBillCurrency"></span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillHeaderTitle">Date d'échéance</span>
                                <span className="repayItemBillHeaderAmount">{repayDetailInfo.repayDate}</span>
                                <span className="repayItemBillCurrency"></span>
                            </div>

                            <span className='repayRowLine'></span>

                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Montant du prêt</span>
                                <span className="repayItemBillItemAmount">{repayDetailInfo.amount}</span>
                                <span className="repayItemBillCurrency">{repayDetailInfo.currency}</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Intérêt</span>
                                <span className="repayItemBillItemAmount">{repayDetailInfo.interest}</span>
                                <span className="repayItemBillCurrency">{repayDetailInfo.currency}</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Frais de service</span>
                                <span className="repayItemBillItemAmount">{repayDetailInfo.repayProFee}</span>
                                <span className="repayItemBillCurrency">{repayDetailInfo.currency}</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Jours de retard</span>
                                <span className="repayItemBillItemAmount">{repayDetailInfo.overdueDay}</span>
                                <span className="repayItemBillCurrency"> jours</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Pénalité de retard</span>
                                <span className="repayItemBillItemAmount">{repayDetailInfo.overdueAmount}</span>
                                <span className="repayItemBillCurrency">{repayDetailInfo.currency}</span>
                            </div>
                        </div>
                    </div>

                    {/* 展期还款 */}
                    {repayDetailInfo.canDeferred && <div className="repayPlan">
                        <div className="repayPlanHeader">
                            <div className="repayPlanHeaderContent">
                                <img
                                    className="repayPlanHeaderIcon"
                                    src={icon_uncheck}
                                    alt="" />
                                <span className="repayItemHeaderTitle">Report de remboursement:</span>
                            </div>
                            <span className="repayItemHeaderTips">After paying the extended service charges, your loan can be deferred for closingAprès avoir payé les frais de service étendus, votre prêt peut être reporté pour être clôturé.</span>
                        </div>
                        {/* 展期信息 */}
                        <div className="repayItemList">
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Frais de service étendus</span>
                                <span className="repayItemBillHeaderAmount">{repayDetailInfo.deferredRepay.currentRepayAmount} {repayDetailInfo.currency}</span>
                                <span className="repayItemBillCurrency"></span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillItemTitle">Jours d'extension</span>
                                <span className="repayItemBillHeaderAmount">{repayDetailInfo.deferredRepay.days}</span>
                                <span className="repayItemBillCurrency"> jours</span>
                            </div>

                            {/* 展期日期 */}
                            <div className="repayItemBillContent">
                                <span className="repayItemBillHeaderTitle">Date d'échéance après l'extension</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayRolloverTitle">{repayDetailInfo.deferredRepay.currentRepayTime}</span>
                                <img
                                    className="repayRolloverIcon"
                                    src={icon_repay_rollover}
                                    alt="" />
                                <span className="repayItemBillItemTitle">{repayDetailInfo.deferredRepay.deferredRepayTime}</span>
                            </div>

                            {/* 展期金额 */}
                            <div className="repayItemBillContent">
                                <span className="repayItemBillHeaderTitle">Remboursement total dû</span>
                            </div>
                            <div className="repayItemBillContent">
                                <span className="repayItemBillHeaderTitle">{repayDetailInfo.deferredRepay.deferredRepayAmount} {repayDetailInfo.currency}</span>
                            </div>
                        </div>
                    </div>}
                </div>
            </div>

            <div className="repayBottom">
                <div className="repayBottomAmountContent">
                    <span className="repayBottomAmountTitle">Montant du paiement</span>
                    <span className="repayBottomAmount">{repayDetailInfo.repayAmount} {repayDetailInfo.currency}</span>
                </div>
                <button type="submit" className="repayApplyBtn mainButtonGradient" onClick={onHandleSubmit}>Payer</button>
            </div>

            {/* add home gif dialog */}
            <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} />

            {/* 支付提示弹框 */}
            <PaidAskDialog visible={paidAskMaskVisible} onClose={onHandlePaidAskDialogClose} onDidPaid={onHandleDidPaid} onNotPaid={onHandleNotPaid} />

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}